import { useNavigate, useLocation } from 'react-router-dom'
import { Button, Form, Input } from 'antd'
import { login } from '@/api/user'
import md5 from 'md5'
import storage from '@/libs/storage'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { setUser, setToken } from '@/store/userSlice'

const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()
  const search = location.search.split('=')[1]
  const from = location.state?.from || search || '/'
  const isAuthenticated = storage.get('token')

  useEffect(() => {
    if (isAuthenticated) {
      navigate(from)
    }
  })

  const onFinish = async (values) => {
    const res = await login({
      username: values.username,
      password: md5(values.password)
    })
    storage.set({ token: res.data.token, user: res.data.user })
    dispatch(setUser(res.data.user))
    dispatch(setToken(res.data.token))
    navigate(from)
  }

  return <>
    <div>
      <Form
        labelCol={{
          span: 8
        }}
        wrapperCol={{
          span: 16
        }}
        style={{
          maxWidth: 600
        }}
        onFinish={onFinish}
        autoComplete="off"
        initialValues={{
          username: 'admin',
          password: 'admin'
        }}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: 'Please input your username!'
            }
          ]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: 'Please input your password!'
            }
          ]}>
          <Input.Password />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  </>
}

export default Login